import classes from './index.module.less';

import { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button } from 'antd';
import { Preview } from '@lle/d3-preview';
import { useSize } from '@/hooks/useSize';
import { fetchLayout } from '@/api/layout';
import { PanelInfo, PartsInfo } from './components';

const Viewer = () => {
  const [params] = useSearchParams();
  const container = useRef<HTMLDivElement>(null!);
  const size = useSize(container);
  const [plHangNo, setPlHangNo] = useState<string>();
  const [preview, setPreview] = useState<Preview>();

  useEffect(() => {
    const plHangNo = params.get('plHangNo');
    if (plHangNo) {
      setPlHangNo(plHangNo);
    }
  }, [params]);

  useEffect(() => {
    if (!plHangNo) return;

    const preview = new Preview(plHangNo);

    preview.mount(container.current);

    setPreview(preview);

    const getData = async (plHangNo: string) => {
      const response = await fetchLayout(plHangNo);

      preview.open(response.data);

      // const parts = parseParts(response.data);
      // console.log(parts);
      // const ids = parts.map(item => item.id);
      // 测试代码
      // setInterval(() => {
      //   const change = Math.random() > 0.5;
      //   const data = {
      //     plHangNo,
      //     partList: change ? ids.slice(0, 4) : ids.slice(4, 7),
      //     messageType: change ? 1 : 2,
      //     showInfoType: 1,
      //   };
      //   sendMsg(data);
      // }, 10000);
    };

    getData(plHangNo);

    return () => {
      preview.unmount();

      setPreview(undefined);
    };
  }, [plHangNo]);

  useEffect(() => {
    preview?.resize();
  }, [preview, size]);

  const onClickLeft = () => {
    preview?.focusManager.focus('left');
  };

  const onClickNormal = () => {
    preview?.focusManager.focus('normal');
  };

  const onClickRight = () => {
    preview?.focusManager.focus('right');
  };

  return (
    <div className={classes.root}>
      <div className={classes.container} ref={container}></div>
      <div className={classes.bottom}>
        <Button onClick={onClickLeft}>左侧</Button>
        <Button onClick={onClickNormal}>正常</Button>
        <Button onClick={onClickRight}>右侧</Button>
      </div>
      {plHangNo && <PanelInfo plHangNo={plHangNo} />}
      {preview && <PartsInfo preview={preview} />}
    </div>
  );
};

export default Viewer;

export const parseParts = (data: string) => {
  const result = JSON.parse(data);

  return getParts(result.elements);
};

const getParts = (data: any[]): any[] => {
  const parts = [];

  for (let i = 0; i < data.length; i++) {
    const element = data[i];
    if (element.data.type === 'part') {
      parts.push(element.data.part);
    }
    parts.push(...getParts(element.children));
  }

  return parts;
};
